package com.序列化;

import java.io.*;

public class SerializeUtil {



    public static byte[] serialize(Object obj ){

        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

      try(ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream)){

          objectOutputStream.writeObject(obj);

          objectOutputStream.flush();



      } catch (IOException e) {
          e.printStackTrace();
      }



      return byteArrayOutputStream.toByteArray();


    }

    public  static <T> T deSerialize(byte[] bytes, Class<T> serializeTemplateClass){

        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);


       try( ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream)){

           return  serializeTemplateClass.cast(objectInputStream.readObject());

       } catch (IOException e) {
           e.printStackTrace();
       } catch (ClassNotFoundException e) {
           e.printStackTrace();
       }

           return  null;
    }


    public static Object deSerialize(byte[] bytes){

        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);


        try( ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream)){

            return  objectInputStream.readObject();

        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

        return  null;
    }



}
